package de.koller.worlders.engine.util.console;

import de.koller.worlders.WSea;
import org.lwjgl.input.Keyboard;

public class ConsoleInput extends WSea {

	private boolean open = false;
	private String content = "";
	private ConsoleListener listener;

	@Override
	protected void init() {
		super.init();
		
		listener = new ConsoleListener( wroot );
	}
	
	@Override
	protected void update( int elapsedTime ) {
		super.update( elapsedTime );
		
		if( !open && wroot.getInput().isKeyPressed( Keyboard.KEY_0 ) ) {
			open();
			return;
		} else if( open && wroot.getInput().isKeyPressed( Keyboard.KEY_ESCAPE ) ) {
			open();
			return;
		}
		
		
		if( !open )
			return;
	
		stringText();
	}

	private void stringText() {
		for( Character c : wroot.getInput().getCharactersPressed() ) {
			if( c == '\b' ) {
				if( content.length() > 0 )
					content = content.substring( 0, content.length()-1 );
				continue;
			} else if( c == 0xd ) {
				System.out.println( "last command: " + content );
				listener.handle( content );
				open();
				return;
			}
			
			if( !Character.isIdentifierIgnorable( c ) )
				content += c;
		}
		redim();
	}
	
	private void open() {
		if( open ) {
			wroot.getGui().getMessage().unShow();
			open = false;
		} else {
			open = true;
			redim();
		}
	}
	
	private void redim() {
		wroot.getGui().getMessage().show( content );
	}
	
	public boolean isOpen() {
		return open;
	}

	public String getContent() {
		return content;
	}

	public void clearConent() {
		content = "";
		System.out.println( "command cleared" );
	}
}
